package com.yunban.project.api.text_check.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson2.JSON;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.lkeap.v20240522.LkeapClient;
import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.enums.CorrectionModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.apache.poi.xwpf.usermodel.TextSegment;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author: lijiajun
 * @date: 2024-12-03
 * @version: 1.0
 */
@Slf4j
public class CorrectUtils {

    private final static int MAX_SENTENCE_COUNT = 500;

    // 去除 ----- 及其后面的所有字符
    public static String removeAfterDash(String input) {
        int dashIndex = input.indexOf("-----");
        if (dashIndex != -1) {
            return input.substring(0, dashIndex).trim();
        }
        return input.trim();
    }

    // 获取 ----- 后面的字符串
    public static List<Long> getAfterDash(String input) {
        int dashIndex = input.indexOf("-----");
        if (dashIndex != -1 && dashIndex + 5 < input.length()) {
            String s = input.substring(dashIndex + 5).trim();
            // 将 s 按 空格分割，并返回一个 Long 类型的列表
            if (StringUtils.hasText(s)) {
                return Arrays.stream(s.split(",")).map(Long::parseLong).collect(Collectors.toList());
            }
        }
        return new ArrayList<>();
    }

    public static List<String> sentencePunctuateList() {
//        return Arrays.asList(",", ";", "!", "?", ";", "，", "。", "！", "？", "；");
//        return Arrays.asList(";", "!", "?", "。", "！", "？", "；", "\n", "\\n");
        return Arrays.asList("\n", "\\n");
    }

    public static List<String> sentencePunctuateListV2() {
//        return Arrays.asList(",", ";", "!", "?", ";", "，", "。", "！", "？", "；");
        return Arrays.asList(";", "!", "?", "。", "！", "？", "；", "\n", "\\n");
//        return Arrays.asList("\n", "\\n");
    }

    public static List<TextSegment> punctuateSplitText(String text) {
        // 获取分隔符列表
        List<String> punctuateList = sentencePunctuateList();

        // 将分隔符集合转换为正则表达式
        String regex = punctuateList.stream().map(Pattern::quote).collect(Collectors.joining("|"));

        // 使用split方法，并通过正则表达式进行分割
        List<TextSegment> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        int lastEnd = 0;
        // 从1开始计数
        int order = 1;

        while (matcher.find()) {
            String str = text.substring(lastEnd, matcher.end());
            if (lastEnd != matcher.start() || str.length() == 1) {
                // 添加从上一个分隔符结束位置到当前分隔符开始位置的文本段
                String segmentText = text.substring(lastEnd, matcher.end());
                // 判断segmentText是否包含\n
                if (matcher.group().equals("\n")) {
                    segmentText = segmentText + "\n";
                }
                result.add(new TextSegment(order++, segmentText, lastEnd, matcher.end() - 1));
            }
            lastEnd = matcher.end();
        }

        // 添加最后一个段落到结果列表（如果有的话）
        if (lastEnd < text.length()) {
            result.add(new TextSegment(order, text.substring(lastEnd), lastEnd, text.length() - 1));
        }
        log.info("segments:{}", result.stream().filter(segment -> !segment.getText().isEmpty()).collect(Collectors.toList()));
        // 过滤掉空字符串
        return result.stream().filter(segment -> !segment.getText().isEmpty()).collect(Collectors.toList());
    }


    public static List<TextSegment> punctuateSplitTextV2(String text) {
        // 获取分隔符列表
        List<String> punctuateList = sentencePunctuateList();

        // 将分隔符集合转换为正则表达式
        String regex = punctuateList.stream().map(Pattern::quote).collect(Collectors.joining("|"));

        // 使用split方法，并通过正则表达式进行分割
        List<TextSegment> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        int lastEnd = 0;
        // 从1开始计数
        int order = 1;

        while (matcher.find()) {
            String str = text.substring(lastEnd, matcher.end());
            if (lastEnd != matcher.start() || str.length() == 1) {
                // 检查当前匹配的分隔符后面是否紧跟闭合引号
                if (matcher.end() < text.length() && text.charAt(matcher.end()) == '”') {
                    // 如果当前匹配的分隔符是句号或其他标点符号，并且后面紧跟闭合引号
                    String segmentText = text.substring(lastEnd, matcher.end() + 1);
                    // 判断segmentText是否包含\n
                    if (matcher.group().equals("\n")) {
                        segmentText = segmentText + "\n";
                    }
                    result.add(new TextSegment(order++, segmentText, lastEnd, matcher.end()));
                    lastEnd = matcher.end() + 1;
                } else {
                    // 按照普通的分隔符进行分割
                    String segmentText = text.substring(lastEnd, matcher.end());
                    // 判断segmentText是否包含\n
                    if (matcher.group().equals("\n")) {
                        segmentText = segmentText + "\n";
                    }
                    result.add(new TextSegment(order++, segmentText, lastEnd, matcher.end()));
                    lastEnd = matcher.end();
                }
            }
        }

        // 添加最后一个段落到结果列表（如果有的话）
        if (lastEnd < text.length()) {
            result.add(new TextSegment(order, text.substring(lastEnd), lastEnd, text.length() - 1));
        }

        // 过滤掉空字符串
        return result.stream().filter(segment -> !segment.getText().isEmpty()).collect(Collectors.toList());
    }

    public static List<TextSegment> punctuateSplitTextV3(String text, int sentencesPerSegment) {
        // 获取分隔符列表
        List<String> punctuateList = sentencePunctuateListV2();

        // 将分隔符集合转换为正则表达式
        String regex = punctuateList.stream().map(Pattern::quote).collect(Collectors.joining("|"));

        // 使用split方法，并通过正则表达式进行分割
        List<TextSegment> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        int lastEnd = 0;
        // 从1开始计数
        int order = 1;
        int currentSentenceCount = 0; // 新增：用于记录当前段落中的句子数
        StringBuilder segmentBuilder = new StringBuilder(); // 新增：用于构建当前段落
        int currentStart = 0; // 新增：记录当前段落的起始位置

        while (matcher.find()) {
            String str = text.substring(lastEnd, matcher.end());
            if (lastEnd != matcher.start() || str.length() == 1) {
                String segmentText;

                // 检查当前匹配的分隔符后面是否紧跟闭合引号
                if (matcher.end() < text.length() && text.charAt(matcher.end()) == '”') {
                    // 如果当前匹配的分隔符是句号或其他标点符号，并且后面紧跟闭合引号
                    segmentText = text.substring(lastEnd, matcher.end() + 1);
                    if (matcher.group().equals("\n")) {
                        segmentText = segmentText + "\n";
                    }
                    lastEnd = matcher.end() + 1;
                } else {
                    // 按照普通的分隔符进行分割
                    segmentText = text.substring(lastEnd, matcher.end());
                    lastEnd = matcher.end();
                }

                if (matcher.group().equals("\n")) {
                    segmentText = segmentText + "\n";
                }

                segmentBuilder.append(segmentText); // 添加到当前段落
                currentSentenceCount++; // 增加当前段落的句子计数

                // 当前段落的句子数达到设定值或遇到换行符时，将其添加到结果列表
                if (currentSentenceCount >= sentencesPerSegment || segmentText.contains("\n")) {
                    result.add(new TextSegment(order++, segmentBuilder.toString(), currentStart, lastEnd));
                    segmentBuilder.setLength(0); // 清空StringBuilder以准备下一个段落
                    currentStart = lastEnd; // 更新当前段落的起始位置
                    currentSentenceCount = 0; // 重置计数器
                }
            }
        }

        // 添加最后一个段落到结果列表（如果有的话）
//        if (lastEnd < text.length() || !segmentBuilder.isEmpty()) {
//            result.add(new TextSegment(order, segmentBuilder.toString(), currentStart, text.length()));
//        }

        // 添加最后一个段落到结果列表（如果有未处理完的内容）
        if (lastEnd < text.length()) {
            segmentBuilder.append(text.substring(lastEnd));
            result.add(new TextSegment(order, segmentBuilder.toString(), currentStart, text.length()));
        } else if (!segmentBuilder.isEmpty()) {
            result.add(new TextSegment(order, segmentBuilder.toString(), currentStart, text.length()));
        }

        // 过滤掉空字符串
        List<TextSegment> collect = result.stream().filter(segment -> !segment.getText().isEmpty()).collect(Collectors.toList());

        // 如果没有任何分句的情况，直接返回一个段落
        if (collect.isEmpty()) {
            collect = new ArrayList<>();
            collect.add(new TextSegment(1, text, 0, text.length()));
        }

        return collect;
    }


    // 判断句子的最大数量
    public static void maxSentenceCount(List<TextSegment> punctuateList) {
        if (punctuateList.size() >= MAX_SENTENCE_COUNT) {
            throw new BusinessException("文章过长，请分批次进行上传");
        }
    }

    public static void main(String[] args) {
        String input = "上海市";
        System.out.println(punctuateSplitTextV3(input, 5));
    }

    // 打印开始时间
    public static void printStartTime(CorrectionModel model) {
        // 开始时间
        String pattern = DatePattern.NORM_DATETIME_MS_PATTERN;
        String startTime = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), pattern);
        log.info("{} 开始时间：{}", model, startTime);
    }

    // 打印开始时间
    public static void printEndTime(CorrectionModel model) {
        // 开始时间
        String pattern = DatePattern.NORM_DATETIME_MS_PATTERN;
        String startTime = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), pattern);
        log.info("{} 结束时间：{}", model, startTime);
    }

    public static LkeapClient getLkeapClient(CorrectionConfig config) {
        Credential cred = new Credential(config.getApiKey(), config.getApiSecret());
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(config.getHost());
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        return new LkeapClient(cred, "ap-shanghai", clientProfile);
    }

    @Data
    @AllArgsConstructor
    public static class TextSegment {
        private int index;
        private String text;
        private int startIndex;
        private int endIndex;
    }
}
